package com.zt.dev.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zt.dev.system.mapper.SystemRelationMapper;
import com.zt.dev.system.mapper.SystemStructureMapper;
import com.zt.dev.system.pojo.SystemStructure;
import com.zt.dev.system.service.SystemStructureService;
import com.zt.dev.system.vo.SystemStructureVo;
import com.zt.dev.utils.TimeUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;

/**
 * @author 30378
 */
@Service
public class SystemStructureServiceImpl implements SystemStructureService {
    private final SystemStructureMapper mapper;
    private final SystemRelationMapper relationMapper;
    private final TimeUtils timeUnit;

    @Autowired
    public SystemStructureServiceImpl(SystemStructureMapper mapper, TimeUtils timeUnit, SystemRelationMapper relationMapper) {
        this.mapper = mapper;
        this.timeUnit = timeUnit;
        this.relationMapper = relationMapper;
    }

    @Override
    public int addSystem(SystemStructureVo structure) {
        SystemStructure po = new SystemStructure();
        BeanUtils.copyProperties(structure, po);
        po.setCreateTime(timeUnit.getCurrentTime());
        // ToDO 业务处理 添加一些其他信息 例如创建人、关联的指标ID等信息
        return mapper.insert(po);
    }

    /**
     * 删除体系以及其相关联的指标项
     * @param ids
     * @return 影响的条数
     * **/
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int delSystemById(Integer[] ids) {
        int i = mapper.deleteBatchIds(Arrays.asList(ids));
        for (Integer id : ids) {
            if (relationMapper.selectById(id) != null) {
                relationMapper.delSysRelation(id);
            }
        }
        return i;
    }

    /**
     * 体系指标项的修改的信息
     * @param structure
     * @return 影响的条数
     * **/
    @Override
    public int editSystemInfo(SystemStructureVo structure) {
        SystemStructure system = new SystemStructure();
        BeanUtils.copyProperties(structure, system);
        return mapper.updateById(system);
    }

    @Override
    public Object findAllSystemById(Integer id) {
        return mapper.selectById(id);
    }

    @Override
    public Page findAllSystemsByPage(Page page) {
        QueryWrapper queryWrapper = new QueryWrapper();
        return mapper.selectPage(page, queryWrapper);
    }
}
